<template>
	<el-image v-if="status === true" :src="rightSrc" class="huxy-image" :preview-src-list="[rightSrc]" @error="onError" @load="onLoad"></el-image>
	<el-image v-else-if="status === false" :src="rightSrc" class="huxy-image" :preview-src-list="[rightSrc]" @load="onLoad"></el-image>
	<div class="huxy-image" v-else-if="error === true">加载失败<span style="display: none;">{{src}}</span></div>
</template>

<script>
import loadImage from '@/utils/loadImage.js';
import { BASE_URL } from '@/puigins/request.js';
export default {
	props: {
		src: String
	},
	data() {
		return {
			status: null,
			rightSrc: '',
			error: false,
			size:-1,
		};
	},
	created() {
		loadImage(this.src)
			.then(res => {
				this.status = true;
				this.rightSrc = res.src;
				this.size = res.size;
				console.log(res,this.src)
				this.debug("created加载图片成功")
				this.sendEvent();
			})
			.catch(e => {
				this.debug("created加载图片失败")
				this.tryProxy();
			});
	},
	methods: {
		tryProxy() {
			loadImage(BASE_URL + '/img-proxy?url=' + this.src)
				.then(res => {
					this.status = false;
					this.rightSrc = res.src;
					this.size = res.size;
					this.debug("tryProxy加载图片成功")
					this.sendEvent();
				})
				.catch(e => {
					this.debug('tryProxy加载图片失败');
					console.error(e)
					this.error = true;
				});
		},
		debug(msg){
			console.log(msg)
		},
		onError() {},
		onLoad(e) {},
		sendEvent() {
			if (this.$el&&this.$el.querySelector) {
				let img=this.$el.querySelector('img')
				this.$emit('load', {
					width: img.naturalWidth,
					height: img.naturalHeight,
					size: this.size,
					src:this.src
				});
			} else {
				setTimeout(() => {
					this.sendEvent();
				}, 100);
			}
		}
	}
};
</script>

<style lang="scss">
.huxy-image {
	width: 100%;
	height: 100%;
	object-fit: cover;
	display: flex;
	justify-content: center;
	align-items: center;
	img {
		max-width: 100%;
		max-height: 100%;
		width: auto;
		height: auto;
	}
}
</style>
